﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sitecore.Data;
using Sitecore.Collections;
using Sitecore.Data.Items;
using Sitecore.Text;
using Sitecore.Data.Templates;
using Sitecore.Data.Managers;
using Sitecore.ChangesTracker.Archiving;

namespace Sitecore.ChangesTracker.Utils
{
  class Utility
  {
    public static string GetItemTemplatesHash(TemplateItem item)
    {
      ListString ids = new ListString(item.ID.ToString() + "_" + GetTemplateHash(item));
      foreach (TemplateItem ti in item.BaseTemplates)
      {          
        ids.Add(ti.ID.ToString()+"_"+GetTemplateHash(ti));
      }
      return ids.ToString();
    }
    public static int GetTemplateHash(TemplateItem item)
    {
        int? hashCode = TrackerManager.TemplateHashCache.GetRecord(item.ID);
        if (hashCode == null)
        {
            string hash = string.Empty;

            foreach (TemplateFieldItem i in item.Fields)
            {
                TemplateField f = TemplateManager.GetTemplateField(i.ID, item.ID, item.Database);
                hash += f.ID.ToString();
                hash += f.Type;
                hash += f.IsUnversioned;
                hash += f.IsShared;
                hash += f.IsBlob;
            }
            hashCode=hash.GetHashCode();
            TrackerManager.TemplateHashCache.AddRecord(item.ID, (int)hashCode);
        }
        return (int)hashCode;
    }
  }
}
